<?php

namespace App\Http\Controllers\Steward;

use App\Models\Bill\Bill;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis as Redis;

use App\Models\Mall\MallMaster;
use App\Models\Mall\MallUser;
use App\Models\Mall\MallUserRole;

class HomeController extends Controller
{

    public function main(Request $request)
    {

        $menus = [
            [
                'icon' => '/static/images/steward/common/index.png',
                'name' => '首页',
                'sub' => [
                    [
                        'name' => '首页',
                        'link' => '/lar/steward/index'
                    ]
                ]
            ],
            [
                'icon' => '/static/images/steward/common/order.png',
                'name' => '订单中心',
                'sub' => [
                    [
                        'name' => '订单助手',
                        'link' => '/lar/steward/order/1'
                    ],
                    [
                        'name' => '订单查询',
                        'link' => '/lar/steward/order/2'
                    ]
                ],
                'permission' => '100'
            ],
            [
                'icon' => '/static/images/steward/common/menu.png',
                'name' => '商品管理',
                'sub' => [
                    [
                        'name' => '商品列表',
                        'link' => '/lar/steward/goods/list_1'
                    ],
                    [
                        'name' => '批量操作',
                        'link' => '/lar/steward/goods/batch_shelf',
                        'permission' => '201'
                    ]
                ],
                'permission' => '200'
            ],
            [
                'icon' => '/static/images/steward/common/kucun.png',
                'name' => '库存管理',
                'sub' => [
                    [
                        'name' => '库存列表',
                        'link' => '/lar/steward/stock'
                    ],
                    [
                        'name' => '库存上传',
                        'link' => ' /lar/steward/stock/batch_stock'
                    ]
                ],
                'permission' => '203'
            ],
            [
                'icon' => '/static/images/steward/common/price.png',
                'name' => '价格管理',
                'sub' => [
                    [
                        'name' => '价格列表',
                        'link' => '/lar/steward/price'
                    ],
                    [
                        'name' => '价格上传',
                        'link' => ' /lar/steward/price/batch_price'
                    ],
                ],
                'permission' => '202'
            ],
            [
                'icon' => '/static/images/steward/common/manager.png',
                'name' => '经营分析',
                'sub' => [],
                'permission' => ''
            ],
            [
                'icon' => '/static/images/steward/common/yijian.png',
                'name' => '意见分析',
                'sub' => [],
                'permission' => ''
            ]
        ];

        $userId = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $mall_id = Redis::get('WDH_STEWARD_MALL_ID_' . session_id());
        $user = MallUser::find($userId);
        $mall = MallMaster::find($mall_id);

        $return_data = [
            'left_menus' => $menus,
            'userName' => $user->name,
            'mallName' => $mall->mallName,
            'domain_name' => $request->getSchemeAndHttpHost(),
            'pc_client' => 0
        ];

        $http_user_agent = $request->server('HTTP_USER_AGENT');
        if ( strpos($http_user_agent, '.NET') ) {
            $return_data['pc_client'] = 1;
        }

        $role = MallUserRole::find($user->roleId);
        $permission = json_decode($role->rolePermission, true);

        foreach($menus as $key=>$m) {
            if (isset($m['permission']) && !array_intersect(explode(',', $m['permission']), $permission)) {
                unset($return_data['left_menus'][$key]);
                continue;
            }
            if (isset($m['sub']) && !empty($m['sub'])) {
                foreach($m['sub'] as $k=>$sub) {
                    if (isset($sub['permission']) && !array_intersect(explode(',', $sub['permission']), $permission))
                        unset($return_data['left_menus'][$key]['sub'][$k]);
                }
            }
        }

        if ($user->userType == 2) {
            $mall_list = MallMaster::where('mallareaID', $user->mallareaID)->get();
            if ($mall_list->oucnt() > 0) {
                foreach($mall_list as $mall) {
                    $return_data['mall'][] = [
                        'mallID' => $mall->mallID,
                        'mallName' => $mall->mallName,
                        'mallCode' => $mall->mallCode
                    ];
                }
            }
        }

        return view('steward/main', $return_data);

    }

    /**
     * 首页页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        $user_id = Redis::get('WDH_STEWARD_USER_ID_' . session_id()) ? Redis::get('WDH_STEWARD_USER_ID_' . session_id()) : 2;
        $mall_id = Redis::get('WDH_STEWARD_MALL_ID_' . session_id()) ? Redis::get('WDH_STEWARD_MALL_ID_' . session_id()) : 1;
        $user = MallUser::find($user_id);

        if($user->userType == 2){  //门店组
            if(!$mall_id){
                return response()->json(array(
                    'code' => 100001,
                    'message' => '请先选择门店'
                ));
            }
            $mall_list = MallMaster::where('mallID',$mall_id)->where('mallareaID',$user['mallareaID'])->first();
            if(!$mall_list){
                return response()->json(array(
                    'code' => 100002,
                    'message' => '所选门店mallID:['.$mall_id.']不在门店组包含范围内'
                ));
            }
        }
        $mall = MallMaster::find($mall_id);

        //查询今日
        $where = [
            ['mallID', $mall_id],
            ['split_type', '<>', 2],
            ['createTime', '>=', date('Y-m-d 00:00:00')],
            ['createTime', '<=', date('Y-m-d H:i:s')]
        ];

        //今日营业额

        $finish_price = Bill::where($where)
                            ->where('bill_status',4)
                            ->where(function($query) {
                                $query->where('pay_type', '=', 1)
                                    ->orWhere(function ($query) {
                                        $query->where('pay_type', 2)
                                                ->where('pay_status', 1);
                                });
                            })
                            ->sum('bill_payable');

        //今日总订单

        $all_bill = Bill::where($where)
                        ->where(function($query) {
                            $query->where('pay_type', 1)
                                ->orWhere(function ($query) {
                                    $query->where('pay_type', 2)
                                          ->where('pay_status', 1);
                                });
                            })
                            ->count();

        //今日客单价
        $one_price = Bill::where($where)
                            ->where('bill_status',4)
                            ->where(function($query) {
                                    $query->where('pay_type', '=', 1)
                                        ->orWhere(function ($query) {
                                            $query->where('pay_type', 2)
                                                 ->where('pay_status', 1);
                                        });
                                })
                            ->avg('bill_payable');

        //订单信息
        $where = [
            ['mallID', $mall_id],
            ['split_type', '<>', 2],
        ];

        $bill_new = Bill::where($where)     //新订单
                        ->where('bill_status', 1)
                        ->where('order_receive', 0)
                        ->where('hang_up', 0)
                            ->where(function($query) {
                                $query->where('pay_type', 1)
                                    ->orWhere(function ($query) {
                                        $query->where('pay_type', 2)
                                              ->where('pay_status', 1);
                                });
                            })
                            ->count();

        $bill_ready = Bill::where('split_type','<>',2)  //代发配送
                        ->where(['mallID'=>$mall_id,'order_receive'=>1])
                        ->where('hang_up','<>',1)
                        ->where(function ($query){
                                $query->where('pay_type',1)
                                    ->orWhere(function ($query){
                                            $query->where('pay_type',2)
                                                ->where('pay_status',1);
                                        });
                                })
                        ->whereNotIn('bill_status',[0,4,5])
                        ->count();

        $bill_hangup = Bill::where($where)   //异常单
                            ->where(function($query){
                                $query->where('pay_type', 1)
                                            ->where('hang_up', 1)
                                        ->orWhere(function($query) {
                                            $query->where('pay_type', 2)
                                                ->where('pay_status', 1)
                                                ->where('hang_up', 1);
                                 });
                            })
                            ->count();

        $bill_return =Bill::join('takeout_bill', 'bill_master.bill_no','=','takeout_bill.bill_no')  //退单
                        ->where(['bill_master.hang_up'=>0,'bill_master.mallID'=>$mall_id,'bill_master.billType'=>21])
                        ->where('takeout_bill.apply_cancel','>',0)
                        ->where('bill_master.split_type','<>',2)
                        ->where(function ($query){
                                $query->where('pay_type',1)
                                    ->orWhere(function ($query){
                                        $query->where('pay_type',2)
                                            ->where('pay_status',1);
                                        });
                        })->count();

        //催单
        $bill_remind = Bill::join('takeout_bill', 'bill_master.bill_no','=','takeout_bill.bill_no')
                            ->where(['hang_up'=>0,'mallID'=>$mall_id,'takeout_bill.remind'=>1])
                            ->where('split_type','<>',2)
                            ->where(function ($query){
                                            $query->where('pay_type',1)
                                                ->orWhere(function ($query){
                                                    $query->where('pay_type',2)
                                                            ->where('pay_status',1);
                                            });
                            })->count();

        //查询昨日
        $where = [
            ['mallID', $mall_id],
            ['split_type', '<>', 2],
            ['createTime', '>=', date('Y-m-d 00:00:00',strtotime('-1 day'))],
            ['createTime', '<=', date('Y-m-d 59:59:59',strtotime('-1 day'))]
        ];

        //昨日营业额
        $yes_finish_price = Bill::where($where)
                                ->where('bill_status',4)
                                ->where(function($query) {
                                    $query->where('pay_type', '=', 1)
                                            ->orWhere(function ($query) {
                                                    $query->where('pay_type', 2)
                                                        ->where('pay_status', 1);
                                                        });
                                                })
                                ->sum('bill_payable');

        //昨日总订单
        $yes_all_bill = Bill::where($where)
                             ->where(function($query) {
                                $query->where('pay_type', 1)
                                    ->orWhere(function ($query) {
                                        $query->where('pay_type', 2)
                                                ->where('pay_status', 1);
                                             });
                                        })
                        ->count();

        //昨日客单价
        $yes_one_price = Bill::where($where)
                                ->where('bill_status',4)
                                ->where(function($query) {
                                    $query->where('pay_type', '=', 1)
                                        ->orWhere(function ($query) {
                                            $query->where('pay_type', 2)
                                                    ->where('pay_status', 1);
                                                    });
                                        })
                                ->avg('bill_payable');

        //今日营收排名

        $shop = 0;
        $shop_array = [];

        $where = [
            ['bill_status', 4],
            ['split_type','<>', 2],
            ['mallID','>', 0],
            ['createTime', '>=', date('Y-m-d 00:00:00')],
            ['createTime', '<=', date('Y-m-d H:i:s')]
        ];

        $revenue_data = DB::table('bill_master')->select('mallID',DB::raw('SUM(bill_payable) as item'))
                                                ->where($where)
                                                ->where(function($query){
                                                        $query->where('pay_type', 1)
                                                            ->orWhere(function($query){
                                                                $query->where('pay_type', 2)
                                                                        ->where('pay_status', 1);
                                                                     });
                                                                })
                                                ->groupBy('mallID')
                                                ->get();

        if($revenue_data){
            foreach($revenue_data as $revenue){
                if($revenue['mallID'] == $mall_id)
                    $shop = $revenue['item'];
                $shop_array[] = $revenue['item'];
            }

            $min_revenue = min($shop_array);
            $max_revenue = max($shop_array);
            $avg_revenue = round(array_sum($shop_array)/count($shop_array), 2);
            $shop_revenue = $shop;
        }else{
            $min_revenue = 0;
            $max_revenue = 0;
            $avg_revenue = 0;
            $shop_revenue = 0;
        }

        //昨日营收排名
        $yes_shop = 0;
        $yes_shop_array = [];

        $where = [
            ['bill_status', 4],
            ['split_type','<>', 2],
            ['mallID','>', 0],
            ['createTime', '>=', date('Y-m-d 00:00:00',strtotime('-1 day'))],
            ['createTime', '<=', date('Y-m-d 23:59:59',strtotime('-1 day'))]
        ];

        $revenue_data = DB::table('bill_master')->select('mallID',DB::raw('SUM(bill_payable) as item'))
                                                ->where($where)
                                                ->where(function($query){
                                                            $query->where('pay_type', 1)
                                                                ->orWhere(function($query){
                                                                        $query->where('pay_type', 2)
                                                                                ->where('pay_status', 1);
                                                                            });
                                                                    })
                                                ->groupBy('mallID')
                                                ->get();

        if($revenue_data){
            foreach($revenue_data as $revenue){
                if($revenue['mallID'] == $mall_id)
                    $yes_shop = $revenue['item'];
                $yes_shop_array[] = $revenue['item'];
            }

            $yes_min_revenue = min($yes_shop_array);
            $yes_max_revenue = max($yes_shop_array);
            $yes_avg_revenue = round(array_sum($yes_shop_array)/count($yes_shop_array), 2);
            $yes_shop_revenue = $yes_shop;
        }else{
            $yes_min_revenue = 0;
            $yes_max_revenue = 0;
            $yes_avg_revenue = 0;
            $yes_shop_revenue = 0;
        }

        //今日订单效率
        $shopEffic = 0;
        $shopEffic_array = [];

        $res_count = DB::table('bill_master')->select('mallID',DB::raw('AVG(timeStamp-createTime) as t'))
                                            ->where([
                                                        ['bill_status', 1],
                                                        ['split_type', '<>' , 2],
                                                        ['mallID', '>' , 0],
                                                        ['createTime', '>=' , date('Y-m-d 00:00:00')],
                                                        ['createTime', '<=' , date('Y-m-d H:i:s')]
                                                ])
                                            ->whereRaw('timeStamp>=createTime')
                                            ->where(function($query){
                                                $query->where('pay_type', 1)
                                                        ->orWhere('pay_type', 2)
                                                            ->where('pay_status', 1);
                                            })
                                            ->groupBy('mallID')
                                            ->orderBy('t','desc')
                                            ->get();
        if(!$res_count){
            $min_effic = 0;
            $max_effic = 0;
            $avg_effic = 0;
            $shop_effic = 0;
        }else{
            foreach ($res_count as $count){
                if($count['mallID'] == $mall_id)
                    $shopEffic = $count['t'];
                $shopEffic_array[] = $count['t'];
            }

            $max_effic = round(min($shopEffic_array));
            $min_effic = round(max($shopEffic_array));
            $avg_effic = round(array_sum($shopEffic_array)/count($shopEffic_array));
            $shop_effic = round($shopEffic);
        }

        //昨日订单效率
        $yes_shopEffic = 0;
        $yes_shopEffic_array = [];

        $res_count = DB::table('bill_master')->select('mallID',DB::raw('AVG(timeStamp-createTime) as t'))
                                            ->where([
                                                        ['bill_status', 1],
                                                        ['split_type', '<>' , 2],
                                                        ['mallID', '>' , 0],
                                                        ['createTime', '>=' , date('Y-m-d 00:00:00',strtotime('-1 day'))],
                                                        ['createTime', '<=' , date('Y-m-d 59:59:59',strtotime('-1 day'))]
                                                     ])
                                            ->whereRaw('timeStamp>=createTime')
                                            ->where(function($query){
                                                     $query->where('pay_type', 1)
                                                         ->orWhere('pay_type', 2)
                                                            ->where('pay_status', 1);
                                                                })
                                            ->groupBy('mallID')
                                            ->orderBy('t','desc')
                                            ->get();

        if(!$res_count){
            $yes_min_effic = 0;
            $yes_max_effic = 0;
            $yes_avg_effic = 0;
            $yes_shop_effic = 0;
        }else{
            foreach ($res_count as $count){
                if($count['mallID'] == $mall_id)
                    $yes_shopEffic = $count['t'];
                $yes_shopEffic_array[] = $count['t'];
            }

            $yes_max_effic = round(min($yes_shopEffic_array));
            $yes_min_effic = round(max($yes_shopEffic_array));
            $yes_avg_effic = round(array_sum($yes_shopEffic_array)/count($yes_shopEffic_array));
            $yes_shop_effic = round($yes_shopEffic);
        }

        //返回数据数组
        $result_data = array(
            'logo' => $mall->logo,  //店铺logo
            'mall_name' => $user->mallName,  //店铺名
            'finish_price' => $finish_price ? round($finish_price,2) : '0.00',  //今日营业额
            'all_bill' => $all_bill ? $all_bill : 0 ,  //今日订单数
            'one_price' => $one_price ? round($one_price,2) :'0.00',  //今日客单价
            'yes_finish_price' => $yes_finish_price ? round($yes_finish_price,2) : '0.00',  //昨日营业额
            'yes_all_bill' => $yes_all_bill ? $yes_all_bill : 0 ,  //昨日订单数
            'yes_one_price' => $yes_one_price ? round($yes_one_price,2) :'0.00',  //昨日客单价

            'bill_new' => $bill_new,       //新订单
            'bill_ready' => $bill_ready,   //待发配送订单
            'bill_hangup' => $bill_hangup, //异常单
            'bill_return' => $bill_return, //退单
            'bill_remind' => $bill_remind, //催单

            'min_revenue' => $min_revenue,      //今日最低营收
            'max_revenue' => $max_revenue,      //今日最高营收
            'avg_revenue' => $avg_revenue,      //今日平均营收
            'shop_revenue' => $shop_revenue,    //今日本店营收
            'yes_min_revenue' => $yes_min_revenue, //昨日最低营收
            'yes_max_revenue' => $yes_max_revenue, //昨日最高营收
            'yes_avg_revenue' => $yes_avg_revenue, //昨日平均营收
            'yes_shop_revenue' => $yes_shop_revenue, //昨日本店营收

            'min_effic' => $min_effic,     //今日最低效率
            'max_effic' => $max_effic,     //今日最高效率
            'avg_effic' => $avg_effic,      //今日平均效率
            'shop_effic' => $shop_effic,    //今日本店效率
            'yes_min_effic' => $yes_min_effic,  //昨日最低效率
            'yes_max_effic' => $yes_max_effic,  //昨日最高效率
            'yes_avg_effic' => $yes_avg_effic,   //昨日平均效率
            'yes_shop_effic' => $yes_shop_effic, //昨日本店效率
        );

        return view('steward/index',$result_data);
    }

}